# -*- coding: utf-8 -*-

from PyQt4 import Qt, QtGui, QtCore

from FeActor import FeActor
from MovieData import *
from Ui_FeMovie import Ui_FeMovie
from GuiUtils import FormEdit

# форма правки данных по фильму

class FeMovie(FormEdit):
    movie = FormEdit.data
    
    def readonly(self):
        return self.__readonly
    def setReadonly(self, value):
        self.__readonly = value
        self.ui.lineName.setEnabled(not value)
        self.ui.spinYear.setEnabled(not value)
        self.ui.lineDirector.setEnabled(not value)
        self.ui.btnAdd.setEnabled(not value)
        self.ui.btnEdit.setEnabled(not value)
        self.ui.btnDelete.setEnabled(not value)
        self.ui.btnImageBrowse.setEnabled(not value)
        self.ui.textDescription.setEnabled(not value)
        self.ui.btnOk.setEnabled(not value)


    def __init__(self, parent=None, movie=None):
        FormEdit.__init__(self, parent)

        self.__readonly = False

        self.ui = Ui_FeMovie()
        self.ui.setupUi(self)


        self.connect(self.ui.btnOk, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('accept()'))
        self.connect(self.ui.btnCancel, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('reject()'))

        self.connect(self.ui.btnOk, QtCore.SIGNAL('clicked()'), self.fromScreenToData)
        self.connect(self.ui.lineName, QtCore.SIGNAL('textEdited(QString)'), self.updateDialogTitle)
        self.connect(self.ui.btnImageBrowse, QtCore.SIGNAL('clicked()'), self.browseImage)
        
        self.connect(self.ui.btnAdd, QtCore.SIGNAL('clicked()'), self.btnAdd_clicked)
        self.connect(self.ui.btnEdit, QtCore.SIGNAL('clicked()'), self.btnEdit_clicked)
        self.connect(self.ui.btnDelete, QtCore.SIGNAL('clicked()'), self.btnDelete_clicked)

        self.movie = movie
    
    # это метод, который используется в FormEdit в файле GuiUtils.py
    def defaultValue(self):
        return Movie()

    def fromScreenToData(self):
        self.movie.name = self.ui.lineName.text()
        self.movie.director = self.ui.lineDirector.text()
        self.movie.year = self.ui.spinYear.value()

        self.movie.actors = [unicode(item.data(QtCore.Qt.EditRole).toPyObject()) for item in self.ui.listActors.findItems("", QtCore.Qt.MatchStartsWith)]

        bytes = Qt.QByteArray()
        buf = Qt.QBuffer(bytes)
        buf.open(QtCore.QIODevice.WriteOnly)
        pixmap = self.ui.graphicsView.items()[0].pixmap()
        if pixmap is not None:
            pixmap.save(buf, "PNG")
        self.movie.cover = buf.data().data()

        self.movie.description = self.ui.textDescription.toHtml()


    def fromDataToScreen(self):
        self.ui.lineName.setText(self.movie.name)
        self.ui.lineDirector.setText(self.movie.director)
        self.ui.spinYear.setValue(self.movie.year)

        listActors = self.ui.listActors
        listActors.clear()
        for item in self.movie.actors:
            listActors.addItem(item)

        pixmap = QtGui.QPixmap()
        if self.movie.cover is None:
            pixmap.fill()
        else:
            pixmap.loadFromData(Qt.QByteArray(self.movie.cover))
        self.setPixmap(pixmap)

        self.ui.textDescription.setHtml(Qt.QString(self.movie.description))

        self.updateDialogTitle(self.ui.lineName.text())

        


    def btnAdd_clicked(self):
        feActor = FeActor()
        if feActor.exec_():
            self.ui.listActors.addItem(feActor.actor)

    def btnEdit_clicked(self):
        feActor = FeActor()
        feActor.actor = self.ui.listActors.item(self.ui.listActors.currentRow()).data(QtCore.Qt.EditRole).toPyObject()
        if feActor.exec_():
            self.ui.listActors.item(self.ui.listActors.currentRow()).setData(QtCore.Qt.EditRole, feActor.actor)

    def btnDelete_clicked(self):
        self.ui.listActors.takeItem(self.ui.listActors.currentRow())

    def updateDialogTitle(self, s):
        message = u"Создать фильм {0}"
        if not self.isNew:
            message = u"Править фильм {0}"
        self.setWindowTitle(message.format(unicode(s)))

    def browseImage(self):
        dialog = QtGui.QFileDialog(self, u"Открыть картинку", "~", u"Картинка (*.png *.jpg)")
        res = dialog.exec_()
        files = dialog.selectedFiles()
        if files.count() == 0:
            return
        filename = files[0]

        pixmap = QtGui.QPixmap()
        pixmap.load(filename, "")
        self.setPixmap(pixmap)

    def setPixmap(self, pixmap):
        scene = QtGui.QGraphicsScene()
        scene.addPixmap(pixmap)
        self.ui.graphicsView.setScene(scene)


# для тестирования, вызывается при запуске этого файла как main
if __name__ == "__main__":
    app = QtGui.QApplication([])
    dialog = FeMovie()
    dialog.show()
    app.exec_()

